package edu.hawaii.halealohacli.kmj;

import org.wattdepot.client.WattDepotClient;

/**
 * Retrieves 24 hours of baseline power consumption data for a specified date.
 * Command syntax: set-baseline [tower | lounge] [date].
 * 
 * @author Jordan Takayama
 */
public class SetBaseline implements Command {

  /**
   * The object which holds the baseline energy consumption readings (in kWh).
   */
  private Baseline baselineData;

  /**
   * The constructor for a SetBaseline object. This constructor does not perform input checking,
   * which is assumed to be performed by the class which calls this constructor.
   * 
   * @param client The WattDepot client used to retrieve energy consumption data.
   * @param location The name of the tower or lounge for which baseline data is retrieved.
   * @param date The date for which baseline data is being retrieved.
   * @throws Exception If a method call within the method throws an exception.
   */
  public SetBaseline(WattDepotClient client, String location, String date) throws Exception {
    if (client.isHealthy()) {
      this.baselineData = new Baseline(client, client.getSource(location), date);
    }
    else {
      throw new Exception("WattDepot server is down or is inaccessible from this device.\n"
          + "Baseline data could not be retrieved.");
    }
  }
  
  /**
   * Retrieves the Baseline which stores the energy consumption values.
   * 
   * @return  The Baseline which stores the energy consumption values.
   */
  public Baseline getBaselineData() {
    return this.baselineData;
  }

  /**
   * Sets the Baseline which stores the energy consumption values.
   * 
   * @param baseline The Baseline which stores the energy consumption values.
   */
  public void setBaseline(Baseline baseline) {
    this.baselineData = baseline;
  }

  /**
   * Prints the results of the Command's query to the command line.
   */
  @Override
  public void printResult() {
    double[] data = baselineData.getBaselineValues();
    System.out.format("Baseline for %s on %s:\n", baselineData.getSourceName(),
        baselineData.getBaselineDate());
    // Print all data values and their corresponding times in order.
    for (int i = 0; i < data.length; i++) {
      if (i < 9) {
        System.out.format("(0%s:00 - 0%s:00 hours)\t%.2f kWh\n", i, i + 1, data[i]);
      }
      else if (i == 9) {
        System.out.format("(0%s:00 - %s:00 hours)\t%.2f kWh\n", i, i + 1, data[i]);
      }
      else if (i < data.length - 1) {
        System.out.format("(%s:00 - %s:00 hours)\t%.2f kWh\n", i, i + 1, data[i]);
      }
      else if (i == data.length - 1) {
        System.out.format("(%s:00 - 00:00 hours)\t%.2f kWh\n", i, data[i]);
      }
    }
  }
}
